package com.alibaba.citrus.ots.platform.enhance.facade.service.scitem;

import com.alibaba.citrus.ots.platform.enhance.functions.item.ScItemEntity;
import com.alibaba.citrus.ots.platform.enhance.model.dto.ScItemFeatureUpdateDTO;
import com.alibaba.citrus.ots.platform.enhance.repository.ScItemRepository;
import com.alibaba.cz.base.tool.log.Log;
import com.alibaba.cz.base.tool.message.ErrorMessage;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.lattice2.epoch.sdk.model.Result;
import com.epoch.app.bcots.model.dto.BaselineEditScItemFeature2Request;
import com.epoch.app.bcots.model.dto.BaselineQueryScItemByPageRequest;
import com.epoch.app.bcots.model.dto.PageQueryScItemListRequest;
import com.epoch.app.bcots.model.dto.PageQueryScItemListResponse;
import com.epoch.app.bcots.service.BaseDataService;
import com.epoch.app.otsplatformenhance.api.scitemwrite.dto.BatchUpdateScItemFeaturesRequest;
import com.epoch.app.otsplatformenhance.api.scitemwrite.dto.EditScItemRelCategoryForImportRequest;
import com.epoch.app.otsplatformenhance.api.scitemwrite.dto.UpdateScItemFeaturesRequest;
import com.epoch.app.otsplatformenhance.api.scitemwrite.service.ScItemWriteService;
import com.epoch.app.otsplatformenhance.dto.request.EditScItemRequest;
import com.epoch.app.otsplatformenhance.model.dto.ImportScItemNewReponse;
import com.epoch.app.otsplatformenhance.model.dto.ImportScItemNewRequest;
import com.epoch.app.otsplatformenhance.model.dto.ImportScItemRelCategorySDO;
import com.epoch.app.otsplatformenhance.model.dto.ScItemSDO;
import com.epoch.app.otsplatformenhance.model.enums.ScItemMarkTypeEnum;
import com.google.common.collect.Lists;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * @author zls
 * @description: TODO
 * @date 2021/9/7 15:30
 */
@Primary
@Service
public class ScItemWriteServiceImpl implements ScItemWriteService {

    private static final Log log = Log.getLogger(ScItemWriteServiceImpl.class);

    @Resource
    ScItemRepository scItemRepository;

    @Resource
    BaseDataService baseDataService;


    @Override
    public Result<Boolean> createScItem(ScItemSDO scItemSDO) {
        System.out.println("入参=="+scItemSDO);
        ScItemEntity scItemEntity = ScItemEntity.of(scItemSDO);
        return Result.success(scItemEntity.doCreate());
    }

    @Override
    public Result<Boolean> editScItem(EditScItemRequest request) {
//        ScItemGroupEntity scItemGroupEntity = ScItemGroupEntity.of(scItemRepository);
//        return Result.success(scItemGroupEntity.doEdit(request));
        return null;
    }

    @Override
    public Result<Boolean> editScItemRelCategory(ScItemSDO scItemSDO) {
        System.out.println("入参=="+scItemSDO);
        ScItemEntity scItemEntity = ScItemEntity.of(scItemSDO);
        return Result.success(scItemEntity.doEdit());
    }

    /**
     * 导入货品类目
     * @param editScItemRelCategoryForImportRequest
     * @return
     * 接口已废弃
     */
    @Override
    public Result<List<ImportScItemRelCategorySDO>> editScItemRelCategoryForImport(EditScItemRelCategoryForImportRequest editScItemRelCategoryForImportRequest) {
/*        List<ImportScItemRelCategorySDO> requestList = editScItemRelCategoryForImportRequest.getRequestList();
        if (CollectionUtils.isEmpty(requestList)) {
            return Result.success(Lists.newArrayList());
        }

        //校验必传参数
        List<ImportScItemRelCategorySDO> checkRequestList = new ArrayList<>();
        for (ImportScItemRelCategorySDO importScItemRelCategorySDO : requestList) {
            if (Strings.isBlank(importScItemRelCategorySDO.getOuterId())) {
                importScItemRelCategorySDO.setErrorMessage(ErrorMessage.code("OTS-01-005-02-15-003", null).getDisplayErrorMessage());
                continue;
            }
            if (Strings.isBlank(importScItemRelCategorySDO.getLeafCategoryId())) {
                importScItemRelCategorySDO.setErrorMessage(ErrorMessage.code("OTS-01-005-02-15-007", null).getDisplayErrorMessage());
                continue;
            }
            checkRequestList.add(importScItemRelCategorySDO);
        }
        if (checkRequestList == null || checkRequestList.size() == 0) {
            return Result.success(requestList);
        }
        for (ImportScItemRelCategorySDO importScItemRelCategorySDO : checkRequestList) {
            EditScItemRelCategoryRequest editScItemRelCategoryRequest = new EditScItemRelCategoryRequest();
            editScItemRelCategoryRequest.setCategoryId(importScItemRelCategorySDO.getLeafCategoryId());
            editScItemRelCategoryRequest.setOuterId(importScItemRelCategorySDO.getOuterId());
            editScItemRelCategoryRequest.setType("0");
            EditScItemRelCategoryResponse editScItemRelCategoryResponse = baseDataService.editScItemRelCategory(editScItemRelCategoryRequest);
            String message = editScItemRelCategoryResponse.getMessage();
            if (StringUtils.isNotBlank(message)) {
                importScItemRelCategorySDO.setErrorMessage(message);
            }
        }*/
        return Result.success(Lists.newArrayList());
    }

    /**
     * 更新货品扩展信息_货品打标
     * @param updateScItemFeaturesRequest
     */
    @Override
    public Result<Boolean> updateScItemFeatures(UpdateScItemFeaturesRequest updateScItemFeaturesRequest) {
        log.info("更新货品features入参={}", JSONObject.toJSONString(updateScItemFeaturesRequest));
        if (StringUtils.isEmpty(updateScItemFeaturesRequest.getScItemId())) {
            return Result.fail(false, "OTS-01-005-02-15-012", ErrorMessage.code("OTS-01-005-02-15-012", null).getDisplayErrorMessage());
        }
        if (StringUtils.isNotEmpty(updateScItemFeaturesRequest.getMark()) && null == ScItemMarkTypeEnum.of(updateScItemFeaturesRequest.getMark())) {
            return Result.fail(false, "OTS-01-005-02-15-013", ErrorMessage.code("OTS-01-005-02-15-013", null).getDisplayErrorMessage());
        }
        //添加标记
        BaselineEditScItemFeature2Request baselineEditScItemFeatureRequest = new BaselineEditScItemFeature2Request();
        ScItemFeatureUpdateDTO scItemFeatureUpdateDTO = new ScItemFeatureUpdateDTO();
        scItemFeatureUpdateDTO.setScItemId(updateScItemFeaturesRequest.getScItemId());
        Map<String, String> addFeaturesMap = new HashMap<>();
        Set<String> set = new HashSet<>();
        if (StringUtils.isEmpty(updateScItemFeaturesRequest.getMark())) {
            set.add("scItemMarkType");
        } else {
            addFeaturesMap.put("scItemMarkType", updateScItemFeaturesRequest.getMark());
        }
        scItemFeatureUpdateDTO.setAddFeatureMap(addFeaturesMap);
        scItemFeatureUpdateDTO.setRemoveFeatureKeyList(set);
        List<ScItemFeatureUpdateDTO> featureUpdateList = new ArrayList<>();
        featureUpdateList.add(scItemFeatureUpdateDTO);
        baselineEditScItemFeatureRequest.setFeatureUpdateList(featureUpdateList);
        log.info("中台更新货品features入参={}", JSONObject.toJSONString(baselineEditScItemFeatureRequest));
        try {
            Result<Void> result = baseDataService.baselineEditScItemFeature2(baselineEditScItemFeatureRequest);
            log.info("中台更新货品features出参={}", JSONObject.toJSONString(result));
            if (result.isSuccess()) {
                return Result.success(true);
            }
            return Result.fail(false, result.getErrorCode(), result.getMessage());
        } catch (Exception e) {
            log.error("更新货品features服务异常={}", e);
            return Result.fail(false, "OTS-01-005-02-15-014", ErrorMessage.code("OTS-01-005-02-15-014", null).getDisplayErrorMessage());
        }
    }

    /**
     * 批量更新货品扩展信息_货品打标
     * @param batchUpdateScItemFeaturesRequest
     */
    @Override
    public Result<Boolean> batchUpdateScItemFeatures(BatchUpdateScItemFeaturesRequest batchUpdateScItemFeaturesRequest) {
        log.info("更新货品features入参={}", JSONObject.toJSONString(batchUpdateScItemFeaturesRequest));
        List<String> scItemIds = batchUpdateScItemFeaturesRequest.getScItemIds();
        String mark = batchUpdateScItemFeaturesRequest.getMark();

        if (CollectionUtils.isEmpty(scItemIds)) {
            return Result.fail(false, "OTS-01-005-02-15-012", ErrorMessage.code("OTS-01-005-02-15-012", null).getDisplayErrorMessage());
        }
        if (StringUtils.isNotEmpty(mark) && ScItemMarkTypeEnum.of(mark) == null) {
            return Result.fail(false, "OTS-01-005-02-15-013", ErrorMessage.code("OTS-01-005-02-15-013", null).getDisplayErrorMessage());
        }

        List<String> failIds = new ArrayList<>();
        for(String scItemId : scItemIds){
            //添加标记
            BaselineEditScItemFeature2Request baselineEditScItemFeatureRequest = new BaselineEditScItemFeature2Request();
            ScItemFeatureUpdateDTO scItemFeatureUpdateDTO = new ScItemFeatureUpdateDTO();
            scItemFeatureUpdateDTO.setScItemId(scItemId);
            Map<String, String> addFeaturesMap = new HashMap<>();
            Set<String> removeFeatureKeySet = new HashSet<>();
            if (StringUtils.isEmpty(mark)) {
                removeFeatureKeySet.add("scItemMarkType");
            } else {
                addFeaturesMap.put("scItemMarkType", mark);
            }
            scItemFeatureUpdateDTO.setAddFeatureMap(addFeaturesMap);
            scItemFeatureUpdateDTO.setRemoveFeatureKeyList(removeFeatureKeySet);
            List<ScItemFeatureUpdateDTO> featureUpdateList = new ArrayList<>();
            featureUpdateList.add(scItemFeatureUpdateDTO);
            baselineEditScItemFeatureRequest.setFeatureUpdateList(featureUpdateList);
            log.info("中台更新货品features入参={}", JSONObject.toJSONString(baselineEditScItemFeatureRequest));
            try {
                Result<Void> result = baseDataService.baselineEditScItemFeature2(baselineEditScItemFeatureRequest);
                log.info("中台更新货品features出参={}", JSONObject.toJSONString(result));
                if(!result.isSuccess()){
                    failIds.add(scItemId);
                }
            } catch (Exception e) {
                log.error("更新货品features服务异常={}", e);
                failIds.add(scItemId);
            }
        }

        Result result = Result.success(true);
        if(CollectionUtils.isEmpty(failIds)){
            result.setMessage("批量更新成功！");
        }else{
            if(failIds.size() == scItemIds.size()){
                result.setSuccess(false);
                result.setMessage("批量更新失败！");
            }else{
                result.setSuccess(false);
                result.setMessage("部分更新成功！");
                Map<String,Object> ext = new HashMap<>();
                ext.put("failScItemIds",failIds.toString());
                result.setExt(ext);
            }
        }
        return result;
    }

    //导入标记新品
    @Override
    public Result<ImportScItemNewReponse> importScItemNew(ImportScItemNewRequest importScItemNewRequest) {
        ImportScItemNewReponse importScItemNewReponse = new ImportScItemNewReponse();
        try {
            if (StringUtils.isBlank(importScItemNewRequest.getOuterId())) {
                importScItemNewReponse.setMessage("货品编码不能为空");
            }
            String scItemId = getScItemIdByOutCode(importScItemNewRequest.getOuterId().trim());
            if (StringUtils.isBlank(scItemId)) {
                importScItemNewReponse.setMessage("货品编码错误");
            }

            String mark = "01";
            //添加标记
            BaselineEditScItemFeature2Request baselineEditScItemFeatureRequest = new BaselineEditScItemFeature2Request();
            ScItemFeatureUpdateDTO scItemFeatureUpdateDTO = new ScItemFeatureUpdateDTO();
            scItemFeatureUpdateDTO.setScItemId(scItemId);
            Map<String, String> addFeaturesMap = new HashMap<>();
            Set<String> set = new HashSet<>();
            if (importScItemNewRequest.getFresh() == null) {
                set.add("scItemMarkType");
            } else {
                addFeaturesMap.put("scItemMarkType", mark);
            }
            scItemFeatureUpdateDTO.setAddFeatureMap(addFeaturesMap);
            scItemFeatureUpdateDTO.setRemoveFeatureKeyList(set);
            List<ScItemFeatureUpdateDTO> featureUpdateList = new ArrayList<>();
            featureUpdateList.add(scItemFeatureUpdateDTO);
            baselineEditScItemFeatureRequest.setFeatureUpdateList(featureUpdateList);
            log.info("importScItemNew中台更新货品features入参={}", JSONObject.toJSONString(baselineEditScItemFeatureRequest));
            Result<Void> result = baseDataService.baselineEditScItemFeature2(baselineEditScItemFeatureRequest);
            log.info("中台更新货品features出参={}", JSONObject.toJSONString(result));
            if (result == null && !result.isSuccess()) {
                importScItemNewReponse.setMessage("标记失败");
            }
        }catch (Throwable e){
            log.error("importScItemNewError:{},request:{}",e.getMessage(),JSON.toJSONString(importScItemNewRequest));
            importScItemNewReponse.setMessage("标记异常");
        }
        return Result.success(importScItemNewReponse);
    }

    public  String getScItemIdByOutCode(String outCode){
//        String code = deleteZeroPrefix(outCode);
        String code = subStringScItmCode(outCode);
        if (org.apache.commons.lang3.StringUtils.isNotBlank(code)){
            BaselineQueryScItemByPageRequest baselineQueryScItemByPageRequest = new BaselineQueryScItemByPageRequest();
            baselineQueryScItemByPageRequest.setOutIdList(Lists.newArrayList(code));
            baselineQueryScItemByPageRequest.setLimit(500);
            Object obj = baseDataService.baselineQueryScItemByPage(baselineQueryScItemByPageRequest);
            if (obj != null){
                JSONObject jsonObject = JSON.parseObject(JSON.toJSONString(obj));
                if (jsonObject != null){
                    jsonObject = jsonObject.getJSONObject("result");
                    if (jsonObject != null){
                        jsonObject = jsonObject.getJSONObject("result");
                        if (jsonObject != null){
                            JSONArray array = jsonObject.getJSONArray("searchResult");
                            if (array != null && array.size() > 0){
                                return array.getJSONObject(0).getString("scItemId");
                            }
                        }
                    }
                }
            }
        }
        return null;
    }
    /**
     * 截取scItemCode 固定长度为12
     * @param str
     * @return
     */
    public static String subStringScItmCode(String str){
        if (org.apache.commons.lang3.StringUtils.isBlank(str)){
            return null;
        }
        if (str.length()>12){
            return str.substring(str.length()-12);
        }
        return str;
    }
}
